export interface DormitoryMember {
  studentId: string;
  name: string;
  gender: string;
  class: string;
}

export interface Dormitory {
  id: number;
  buildingName: string;
  roomNumber: string;
  capacity: number;
  members: DormitoryMember[];
  gender: string;
}

export interface DormitoryBuilding {
  id: number;
  name: string;
  address: string;
  gender: string;
  totalRooms: number;
  occupiedRooms: number;
}

// 从localStorage获取数据或使用默认数据
const STORAGE_KEY_DORMITORIES = 'dormitories';
const STORAGE_KEY_BUILDINGS = 'dormitoryBuildings';

// 模拟宿舍数据
let mockDormitories: Dormitory[] = [];

// 尝试从localStorage加载数据
const savedDormitories = localStorage.getItem(STORAGE_KEY_DORMITORIES);
if (savedDormitories) {
  try {
    mockDormitories = JSON.parse(savedDormitories);
  } catch (error) {
    console.error('加载宿舍数据失败:', error);
  }
}

// 如果没有保存的数据，使用默认数据
if (mockDormitories.length === 0) {
  mockDormitories = [
    {
      id: 1,
      buildingName: '黄悦一期',
      roomNumber: '101',
      capacity: 4,
      gender: '男',
      members: [
        {
          studentId: '2023001',
          name: '张三',
          gender: '男',
          class: '计科1班'
        },
        {
          studentId: '2023003',
          name: '王五',
          gender: '男',
          class: '数科1班'
        }
      ],
      dutySchedule: {
        '周一': ['2023001'],
        '周二': ['2023003'],
        '周三': ['2023001'],
        '周四': ['2023003'],
        '周五': ['2023001'],
        '周六': ['2023003'],
        '周日': ['2023001']
      }
    },
    {
      id: 2,
      buildingName: '黄悦三期',
      roomNumber: '102',
      capacity: 4,
      gender: '男',
      members: [
        {
          studentId: '2023005',
          name: '王二',
          gender: '男',
          class: '信息1班'
        },
        {
          studentId: '2023007',
          name: '王二',
          gender: '男',
          class: '信息1班'
        }
      ],
      dutySchedule: {
        '周一': ['2023005'],
        '周二': ['2023007'],
        '周三': ['2023005'],
        '周四': ['2023007'],
        '周五': ['2023005'],
        '周六': ['2023007'],
        '周日': ['2023005']
      }
    },
    {
      id: 3,
      buildingName: '学8舍',
      roomNumber: '201',
      capacity: 4,
      gender: '女',
      members: [
        {
          studentId: '2023002',
          name: '李四',
          gender: '女',
          class: '软件1班'
        },
        {
          studentId: '2023004',
          name: '赵六',
          gender: '女',
          class: '信息1班'
        }
      ],
      dutySchedule: {
        '周一': ['2023002'],
        '周二': ['2023004'],
        '周三': ['2023002'],
        '周四': ['2023004'],
        '周五': ['2023002'],
        '周六': ['2023004'],
        '周日': ['2023002']
      }
    },
    // 男生1号楼宿舍数据
    {
      id: 4,
      buildingName: '男生1号楼',
      roomNumber: '101',
      capacity: 4,
      gender: '男',
      members: [
      {
        studentId: '2023101',
        name: '陈强',
        gender: '男',
        class: '计算机1班'
      },
      {
        studentId: '2023102',
        name: '刘洋',
        gender: '男',
        class: '计算机1班'
      },
      {
        studentId: '2023103',
        name: '张伟',
        gender: '男',
        class: '计算机1班'
      },
      {
        studentId: '2023104',
        name: '李明',
        gender: '男',
        class: '计算机1班'
      }
    ]
  },
  {
    id: 5,
    buildingName: '男生1号楼',
    roomNumber: '102',
    capacity: 4,
    gender: '男',
    members: [
      {
        studentId: '2023105',
        name: '王浩',
        gender: '男',
        class: '计算机2班'
      },
      {
        studentId: '2023106',
        name: '赵杰',
        gender: '男',
        class: '计算机2班'
      }
    ],
    dutySchedule: {
      '周一': ['2023105'],
      '周二': ['2023106'],
      '周三': ['2023105'],
      '周四': ['2023106'],
      '周五': ['2023105'],
      '周六': ['2023106'],
      '周日': ['2023105']
    }
  },
  {
    id: 6,
    buildingName: '男生1号楼',
    roomNumber: '103',
    capacity: 4,
    gender: '男',
    members: [],
    dutySchedule: {
      '周一': [],
      '周二': [],
      '周三': [],
      '周四': [],
      '周五': [],
      '周六': [],
      '周日': []
    }
  },
  // 女生1号楼宿舍数据
  {
    id: 7,
    buildingName: '女生1号楼',
    roomNumber: '101',
    capacity: 4,
    gender: '女',
    members: [
      {
        studentId: '2023201',
        name: '王丽',
        gender: '女',
        class: '英语1班'
      },
      {
        studentId: '2023202',
        name: '李娜',
        gender: '女',
        class: '英语1班'
      },
      {
        studentId: '2023203',
        name: '张红',
        gender: '女',
        class: '英语1班'
      },
      {
        studentId: '2023204',
        name: '刘芳',
        gender: '女',
        class: '英语1班'
      }
    ],
    dutySchedule: {
      '周一': ['2023201'],
      '周二': ['2023202'],
      '周三': ['2023203'],
      '周四': ['2023204'],
      '周五': ['2023201'],
      '周六': ['2023202'],
      '周日': ['2023203']
    }
  },
  {
    id: 8,
    buildingName: '女生1号楼',
    roomNumber: '102',
    capacity: 4,
    gender: '女',
    members: [
      {
        studentId: '2023205',
        name: '陈静',
        gender: '女',
        class: '英语2班'
      },
      {
        studentId: '2023206',
        name: '赵婷',
        gender: '女',
        class: '英语2班'
      }
    ],
    dutySchedule: {
      '周一': ['2023205'],
      '周二': ['2023206'],
      '周三': ['2023205'],
      '周四': ['2023206'],
      '周五': ['2023205'],
      '周六': ['2023206'],
      '周日': ['2023205']
    }
  }
];
}

// 模拟宿舍楼数据
let mockDormitoryBuildings: DormitoryBuilding[] = [];

// 尝试从localStorage加载数据
const savedBuildings = localStorage.getItem(STORAGE_KEY_BUILDINGS);
if (savedBuildings) {
  try {
    mockDormitoryBuildings = JSON.parse(savedBuildings);
  } catch (error) {
    console.error('加载宿舍楼数据失败:', error);
  }
}

// 如果没有保存的数据，使用默认数据
if (mockDormitoryBuildings.length === 0) {
  mockDormitoryBuildings = [
    {
      id: 1,
      name: '男生1号楼',
      address: '校园东区A段',
      gender: '男',
      totalRooms: 100,
      occupiedRooms: 65
    },
    {
      id: 2,
      name: '女生1号楼',
      address: '校园东区B段',
      gender: '女',
      totalRooms: 100,
      occupiedRooms: 70
    }
  ];
}

// 保存数据到localStorage
const saveDataToStorage = () => {
  try {
    localStorage.setItem(STORAGE_KEY_DORMITORIES, JSON.stringify(mockDormitories));
    localStorage.setItem(STORAGE_KEY_BUILDINGS, JSON.stringify(mockDormitoryBuildings));
  } catch (error) {
    console.error('保存数据失败:', error);
  }
};

// 获取所有宿舍
export const getDormitories = async (): Promise<Dormitory[]> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(mockDormitories);
    }, 300);
  });
};

// 添加新宿舍
export const addDormitory = async (dormitory: Omit<Dormitory, 'id'>): Promise<Dormitory> => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // 检查宿舍容量是否符合4人限制
      if (dormitory.capacity > 4) {
        reject(new Error('宿舍容量不能超过4人'));
        return;
      }
      
      // 检查成员数量是否超过容量
      if (dormitory.members.length > dormitory.capacity) {
        reject(new Error(`成员数量不能超过宿舍容量（${dormitory.capacity}人）`));
        return;
      }
      
      const newDormitory: Dormitory = {
        ...dormitory,
        id: Math.max(...mockDormitories.map(d => d.id), 0) + 1
      };
      mockDormitories.push(newDormitory);
      saveDataToStorage();
      resolve(newDormitory);
    }, 300);
  });
};

// 更新宿舍信息
export const updateDormitory = async (id: number, updatedData: Partial<Dormitory>): Promise<Dormitory | null> => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const index = mockDormitories.findIndex(d => d.id === id);
      if (index !== -1) {
        // 检查宿舍容量是否符合4人限制
        if (updatedData.capacity && updatedData.capacity > 4) {
          reject(new Error('宿舍容量不能超过4人'));
          return;
        }
        
        // 计算更新后的宿舍信息
        const currentDorm = mockDormitories[index];
        const newCapacity = updatedData.capacity || currentDorm.capacity;
        const newMembers = updatedData.members || currentDorm.members;
        
        // 检查成员数量是否超过容量
        if (newMembers.length > newCapacity) {
          reject(new Error(`成员数量不能超过宿舍容量（${newCapacity}人）`));
          return;
        }
        
        mockDormitories[index] = { ...mockDormitories[index], ...updatedData };
        saveDataToStorage();
        resolve(mockDormitories[index]);
      } else {
        resolve(null);
      }
    }, 300);
  });
};

// 删除宿舍
export const deleteDormitory = async (id: number): Promise<boolean> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const initialLength = mockDormitories.length;
      mockDormitories = mockDormitories.filter(d => d.id !== id);
      saveDataToStorage();
      resolve(mockDormitories.length < initialLength);
    }, 300);
  });
};

// 获取所有宿舍楼
export const getDormitoryBuildings = async (): Promise<DormitoryBuilding[]> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(mockDormitoryBuildings);
    }, 300);
  });
};

// 添加新宿舍楼
export const addDormitoryBuilding = async (building: Omit<DormitoryBuilding, 'id'>): Promise<DormitoryBuilding> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const newBuilding: DormitoryBuilding = {
        ...building,
        id: Math.max(...mockDormitoryBuildings.map(b => b.id), 0) + 1
      };
      mockDormitoryBuildings.push(newBuilding);
      saveDataToStorage();
      resolve(newBuilding);
    }, 300);
  });
};

// 更新宿舍楼信息
export const updateDormitoryBuilding = async (id: number, updatedData: Partial<DormitoryBuilding>): Promise<DormitoryBuilding | null> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const index = mockDormitoryBuildings.findIndex(b => b.id === id);
      if (index !== -1) {
        mockDormitoryBuildings[index] = { ...mockDormitoryBuildings[index], ...updatedData };
        saveDataToStorage();
        resolve(mockDormitoryBuildings[index]);
      } else {
        resolve(null);
      }
    }, 300);
  });
};

// 删除宿舍楼
export const deleteDormitoryBuilding = async (id: number): Promise<boolean> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const initialLength = mockDormitoryBuildings.length;
      mockDormitoryBuildings = mockDormitoryBuildings.filter(b => b.id !== id);
      saveDataToStorage();
      resolve(mockDormitoryBuildings.length < initialLength);
    }, 300);
  });
};

// 导出数据以便其他地方使用
export { mockDormitories, mockDormitoryBuildings };